package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;
import java.util.Vector;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.ChildrenMapper;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.IndexRelative;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

public class IndexExpansionConfirmationMsg extends TagapastryMsg {

	public static final int TYPE = 8;
	private static final long serialVersionUID = TYPE;
	private final boolean childIndexCreatedSuccessfully;
	private char childExtension;

	public IndexExpansionConfirmationMsg(Tag tag, NodeHandle sender, boolean success, char childExtension) {
		super(tag, sender);
		this.childIndexCreatedSuccessfully = success;
		this.childExtension = childExtension;
	}

	public IndexExpansionConfirmationMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		this.childIndexCreatedSuccessfully = buf.readBoolean();
		this.childExtension = buf.readChar();
	}
	
	public int getSize() {
		return super.getSize() + 2; //  boolean + char ?
	}

	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);
		if(index == null || index.getChildren() == null)
			return; // Testing
		
//		System.out.println("confirming creation of child " + childExtension +  "  to:   " + tag +  " " + index);
		// get rid of data that has been passed to the child 
		index.cleanDataInChild(childExtension);

		// Tells the index that the child is confirmed, and sends the child any buffered messages
		ChildrenMapper mapper = new ChildrenMapper();
		int childIndex = mapper.get(childExtension);
		IndexRelative child = index.getChildren().get(childIndex);
		child.activate(taga);
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
		buf.writeBoolean(childIndexCreatedSuccessfully);
		buf.writeChar(childExtension);
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}

	@Override
	public short getType() {
		return TYPE;
	}

	@Override
	public String toString() {
		String str = super.toString();
		str += ", success: " + childIndexCreatedSuccessfully + 
		", childExtension: " + childExtension + " }";
		return str;
	}

}
